/**
 * 
 */
package com.gcb.socket;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * create date: 2010-10-21 下午03:49:38
 * @author Angela Tao
 * @version 1.0
 *
 */
public class TalkClient01 extends Thread{
	
	private Socket s;
	private DataInputStream dis;
	private DataOutputStream dos;
	String name = null;

	/**
	 * 
	 */
	public TalkClient01() {
		// TODO Auto-generated constructor stub
	}
	
	public void connect(){
		try {
			s = new Socket("192.2.2.42",4433);
			name = s.getInetAddress().getHostName();
			dis = new DataInputStream(s.getInputStream());
			dos = new DataOutputStream(s.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void listen(){
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String str =  br.readLine();
			while(!"end".equals(str)){
				dos.writeUTF(sendMess(str));
				//dos.writeUTF(str);
				dos.flush();
				str = br.readLine();
			}
			br.close();
			dis.close();
			dos.close();
			s.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TalkClient01 tc = new TalkClient01();
		tc.connect();
		tc.start();
		tc.listen();
	}
	
	public void run() {
		// TODO Auto-generated method stub
		try {
			while(true){
				String str = dis.readUTF();
				getMess(str);
				if("end".equals(str)){
					break;
				}
			}		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void getMess(String str){
		System.out.println(str);
	}
	
	public String sendMess(String str){
		System.out.println("Server: " + str);
		return name + ": " + str;
	}

}
